package it.omnisong.server.index;

import it.omnisong.client.model.Song;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class DBIndexer {
	private IndexWriter writer;
	
	public static void main(String[] args){
		
		//ricordarsi prima di testarlo di aggiornare l'indexpath!
		String indexPath="/home/alessio/workspace/OmniSong/indexes/";
		try{
			DBIndexer dbi = new DBIndexer(indexPath);
			dbi.indexDB();
		}catch(Exception e){
			e.printStackTrace();
		}
	//	try{
	//		DBIndexer dbi=new DBIndexer(indexPath);
	//		dbi.indexDBwithoutConnection();
	//	}catch(Exception f){
	//			f.printStackTrace();
			
	//	}
	}
	
	/**
	 * solo per testare se funziona (no connessione a Postgres)
	 */
	public void indexDBwithoutConnection(){
		Song[] songs=new Song[2];
		Song temp=(Song) new Song();
		temp.setArtist("Depeche Mode");
		temp.setTitle("Personal Jesus");
		temp.setLyric("Your own your own, personal, Jesus! Reach out and touch faith");
		songs[0]=temp;
		temp.setArtist("Led Zeppelin");
		temp.setTitle("Immigrant Song");
		temp.setLyric("Ah-ah-ah we came from the land of the ice and snow from" +
				"the midnight sun and the hot spring blow. The hammer of the Gods" +
				"will drive our ships to new land, fighting the horde, singing" +
				"and crying Valhalla I'm coming!");
		songs[1]=temp;
		
		for (Song song : songs){
			String title=song.getTitle();
			String lyric=song.getLyric();
			String artist=song.getArtist();
			
			//inizio indicizzazione
			Document doc=new Document();
			doc.add(new Field("title",title,Field.Store.YES,
					Field.Index.NOT_ANALYZED));
			doc.add(new Field("artist",artist,Field.Store.YES,
					Field.Index.NOT_ANALYZED));
			doc.add(new Field("lyric",lyric,Field.Store.YES,
					Field.Index.NOT_ANALYZED));
			try{
			writer.addDocument(doc);
			}catch(Exception f){
				f.printStackTrace();
			}
		}
			try{
			int numDocs=writer.numDocs();
			
			System.out.println(numDocs+" lyrics added to the index!");
			//close the index
			
			writer.optimize();
			writer.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		
		
	}
	
	public void indexDB(){
		
		/* Connessione al database tramite DBManager
		 * */
	}
	
	public DBIndexer(String indexDir) throws IOException{
		FSDirectory dir = FSDirectory.open(new File(indexDir));
	    writer = new IndexWriter(dir, new StandardAnalyzer(Version.LUCENE_30),
	        true, IndexWriter.MaxFieldLength.LIMITED); 
		
	}

}
